<?php
namespace Modules\Search\Library;

use Phalcon\Http\Client\Provider\Exception;
use Phalcon\Mvc\User\Plugin;
use Modules\Core\Models\Log;

class Search extends Plugin
{
    protected $_project;
    protected $_projectList;
    protected $_search;
    protected $_api;
    /**
     * @var EngineInterface
     */
    protected $_engine;

    public function __construct($project, $search = null)
    {
        $this->getDI();
        $this->_engineList = $this->config->cache('searchEngine');
        $this->_projectList = $this->config->cache('searchProject');

        if (!isset($this->_projectList[$project])) {
            throw new Exception('搜索项目不存在：' . $project);
        }
        $projectInfo = $this->_projectList[$project];
        if (!isset($projectInfo['engine'])) {
            $projectInfo['engine'] = 'xunsearch';
        }

        if (!isset($this->_engineList[$projectInfo['engine']])) {
            throw new Exception('搜索引擎不存在：' . $projectInfo['engine']);
        }
        $projectInfo['id'] = $project;

        $this->_project = $projectInfo;
        $this->_search = $search;

        $engineCallable = $this->_engineList[$this->_project['engine']]['callable'];
        if (!class_exists($engineCallable)) {
            throw new Exception('搜索引擎处理器不存在：' . $engineCallable);
        }
        $this->_engine = new $engineCallable($this->_project['id']);
    }

    public function search($search = null)
    {
        if (!is_null($search)) {
            $this->_search = $search;
        }
        if (is_null($this->_search)) {
            return false;
        }

        return $this->_engine->query($this->_search);
    }

    public function highlight($body)
    {
        return $this->_engine->highlight($body);
    }

    public function getSearch()
    {
        return $this->_search;
    }

    public function hotSearches($num = 10)
    {
        return $this->_engine->hotSearches($num);
    }

    public function relatedSearches($num = 10, $word = null)
    {
        return $this->_engine->relatedSearches($num, $word);
    }

    public function total()
    {
        return $this->_engine->total();
    }

    public function getRoute()
    {
        if (!isset($this->_project['route'])) {
            return $this->getRoute();
        }
        $routeCallable = $this->_project['route'];
        if (!isCallable($routeCallable)) {
            $error = '搜索模块不可调用的回调结构：' . $routeCallable;
            Log::add([
                'data' => $error,
                'type' => 'search',
                'level' => 4
            ]);
            throw new \Exception($error);
        }
        $route = call_user_func($routeCallable, $this);
        return $route;
    }

    protected function _getRoute()
    {

    }
}